package com.liguang.rcs.admin.service;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.liguang.rcs.admin.db.entity.DodmsDriverEntity;
import com.liguang.rcs.admin.db.entity.DodmsUserEntity;
import com.liguang.rcs.admin.db.repository.DodmsDriverRepository;
import com.liguang.rcs.admin.exception.BaseException;
import com.liguang.rcs.admin.util.ResponseCode;
import com.liguang.rcs.admin.util.copy.BeanUtils;
import com.liguang.rcs.admin.util.copy.exception.CopyPropertiesFailException;
import com.liguang.rcs.admin.util.excel.ExcelExport;
import com.liguang.rcs.admin.util.response.PageableBody;
import com.liguang.rcs.admin.web.drivermgr.DriverVO;
import com.liguang.rcs.admin.web.user.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import javax.transaction.Transactional;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
@Slf4j
public class DriverMgrService {
    private static final String EXCEL_TEMPLATE_PATH = "/download-template.xlsx";

    @Autowired
    private DodmsDriverRepository repository;

    public PageableBody<DriverVO> queryPage(String name, Date startDate, Date endDate, Integer page, Integer limit, String sort, String order) {
        Pageable pageable = PageRequest.of(page - 1, limit, Sort.Direction.fromString(order), sort);
        Page<DodmsDriverEntity> userPage = repository.findAll(generateSpecification(name, startDate, endDate), pageable);
        return PageableBody.buildFrom(userPage, DriverVO::buildFrom);
    }

    private Specification<DodmsDriverEntity> generateSpecification(String name, Date startDate, Date endDate) {
        return (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> conditionLst = Lists.newArrayList();
            if (!Strings.isNullOrEmpty(name)) {
                conditionLst.add(criteriaBuilder.like(root.get("name"), "%" + name + "%"));
            }
            if (startDate != null && endDate != null) {
                conditionLst.add(criteriaBuilder.between(root.get("updateDate"), startDate, endDate));
            }
            return criteriaBuilder.and(conditionLst.toArray(new Predicate[conditionLst.size()]));
        };
    }

    @Transactional
    public void update(DriverVO driverVO) throws CopyPropertiesFailException {
        Optional<DodmsDriverEntity> driverEntity = repository.findById(driverVO.getId());
        if (!driverEntity.isPresent()) {
            throw new BaseException(ResponseCode.BAD_ARGUMENT_VALUE, "更新的记录不存在");
        }
        BeanUtils.copyProperties(driverVO, driverEntity.get());
        repository.save(driverEntity.get());
    }

    public void add(@Valid DriverVO driverVO) {
        repository.save(driverVO.toEntity());
    }

    public void delete(Long id) {
        repository.deleteById(id);
    }

    public List<String> queryAllCompany() {
        return repository.queryALlCOmpany();
    }

    public DriverVO queryByIdCard(String driverLicense) {
        DodmsDriverEntity entity = repository.findByDriverLicense(driverLicense);
        if (entity != null) {
            return DriverVO.buildFrom(entity);
        }
        return null;
    }

    public Workbook generateWorkbook(String name, Date startDate, Date endDate) throws Exception {
        List<DodmsDriverEntity> entityList = repository.findAll(generateSpecification(name, startDate, endDate));
        ExcelExport export = new ExcelExport(DriverMgrService.class.getResource(EXCEL_TEMPLATE_PATH), 2);
        export.init(true);
        for(DodmsDriverEntity entity : entityList) {
            export.addRow(DriverVO.buildFrom(entity));
        }
        return export.getWorkbook();
    }
}
